package cqie.personal.frame.controller;

import cqie.personal.frame.bo.UserLoginBO;
import cqie.personal.frame.bo.UserRegisterBO;
import cqie.personal.frame.enums.Code;
import cqie.personal.frame.exception.LoginFailException;
import cqie.personal.frame.exception.ValidationFailException;
import cqie.personal.frame.service.UserInfoService;
import cqie.personal.frame.util.JwtUtil;
import cqie.personal.frame.vo.ResultVO;
import cqie.personal.frame.vo.UserView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@ResponseBody
@RequestMapping("/Welcome")
@Api(tags = "用户公共模块")
public class LoginController {

    @Resource
    private UserInfoService userInfoService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public ResultVO login(@RequestBody UserLoginBO userLoginBO , HttpServletResponse response) throws ValidationFailException, LoginFailException {
        UserView user = userInfoService.login(userLoginBO);
        String token = userInfoService.updateToken(user.getUid(),user.getId());
        if(token == null){
            return new ResultVO(Code.USER_LOGIN_FAIL.getCode(),Code.USER_LOGIN_FAIL.getMessage());
        }

        response.addHeader("Access-Control-Expose-headers","token");
        response.addHeader("token",token);
        return new ResultVO(user);
    }
    @ApiOperation("注册")
    @PostMapping("/register")
    public ResultVO register(@RequestBody UserRegisterBO userRegisterBO) throws ValidationFailException {
        if(!userInfoService.register(userRegisterBO)){
            return new ResultVO(Code.OPERATION_FAIL.getCode(),"注册失败了，稍后重试一下吧");
        }
        return new ResultVO();
    }
    @ApiOperation("账号是否存在")
    @GetMapping("/accountValid")
    public ResultVO accountValid(String userAccount ) throws ValidationFailException {
        return new ResultVO(userInfoService.accountValid(userAccount));
    }

    @ApiOperation("uid是否存在")
    @GetMapping("/uidValid")
    public ResultVO uidValid(Integer uid ) throws ValidationFailException {
        return new ResultVO(userInfoService.uidValid(uid));
    }

    @ApiOperation("注销")
    @PutMapping("**/quit")
    public ResultVO quit(HttpServletRequest request , Integer id){
        String token = request.getHeader("token");
        Integer userId = JwtUtil.parsingToken(token).getId();
        if(!userId.equals(id)){
            return new ResultVO(Code.ACCESS_DENIED.getCode(),Code.USER_LOGIN_INVALID_TOKEN.getMessage()+" , " + "不匹配的请求账号");
        }
        if(!userInfoService.quit(id)){
            return new ResultVO(Code.USER_QUIT_FAIL.getCode(),Code.USER_QUIT_FAIL.getMessage());
        }
        return new ResultVO();
    }



}
